package com.zhoug.push.imp;

import android.os.Bundle;
import android.text.TextUtils;

import com.huawei.hms.push.HmsMessageService;
import com.huawei.hms.push.RemoteMessage;
import com.zhoug.common.utils.JsonUtils;
import com.zhoug.logging.Logger;
import com.zhoug.push.core.PushMessage;
import com.zhoug.push.core.PushVendor;

/**
 * 华为消息服务用于接收透传消息、获取Token
 * @description: 类的简要描述
 * @author: 35574
 * @date: 2025/11/3 16:19
 */
public class HuaweiMessageService extends HmsMessageService {
    private static final String TAG = ">>>HuaweiMessageService";
    private static final String VENDOR=PushVendor.HUA_WEI;

    @Override
    public void onNewToken(String token, Bundle bundle) {
        super.onNewToken(token, bundle);
        Logger.d(TAG, "onNewToken2: token:" + token);
        Logger.d(TAG, "onNewToken2: bundle:" + bundle);
        // 判断token是否为空
        if (!TextUtils.isEmpty(token)) {
            PushManager.getInstance().onTokenReceived(token,VENDOR);
        }
    }

    @Override
    public void onTokenError(Exception e, Bundle bundle) {
        super.onTokenError(e, bundle);
        Logger.e(TAG, "onTokenError2: token错误: " + e.getMessage());
        Logger.e(TAG, "onTokenError2: token错误 bundle: " + bundle);
        PushManager.getInstance().onTokenError(VENDOR, -1, e.getMessage());
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        Logger.d(TAG, "onMessageReceived: " + JsonUtils.toJson(remoteMessage));
        // 1. 应用在线时，处理透传消息（不会自动显示通知）
        if (remoteMessage.getData() != null && !remoteMessage.getData().isEmpty()) {
            String data = remoteMessage.getData();
            Logger.d(TAG, "onMessageReceived: message:" + data);
            // 开发者可以根据接收到的数据，自定义处理逻辑，例如创建本地通知
            PushMessage pushMessage=new PushMessage();
            pushMessage.setContent(data);
            pushMessage.setVendor(VENDOR);
            PushManager.getInstance().onMessageReceived(VENDOR,pushMessage);
            //发送广播 8.0以后静态注册的广播需要显示发送
//            String packageName = getPackageName();
//            Intent broadcastIntent=new Intent("com.zhoug.push.MESSAGING_EVENT");
//            broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
//            broadcastIntent.putExtra("message",pushMessage);
//            broadcastIntent.putExtra("sendPackageName",packageName);
//            sendBroadcast(broadcastIntent);
        }
        // 2. 处理通知栏消息（应用在线时，消息会同时送达此处和系统通知栏）
        if (remoteMessage.getNotification() != null) {
            Logger.d("HuaweiPush", "Received notification message");
            // 通常系统会自动处理通知展示，但你可以在此处进行拦截或补充逻辑
            Logger.d(TAG, "onMessageReceived: Received notification message");
        }


    }


}
